package com.bite.gateway;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class CustomGatewayFilterFactory extends AbstractGatewayFilterFactory<CustomConfig> implements Ordered {

    public CustomGatewayFilterFactory() {
        super(CustomConfig.class);
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }

    @Override
    public GatewayFilter apply(CustomConfig config) {
        return new GatewayFilter() {

            /**
             *
             * ServerWebExchange：HTTP响应和请求
             * GatewayFilterChain：过滤器链
             * Mono：Reactor的核心类，数据发布者，Mono最多只能触发一次，可以把Mono用在异步完成任务时，发出通知
             */
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                log.info("Pre Filter,config:{}", config);

                return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                    log.info("Post Filter");
                }));
            }
        };
    }
}
